package com.zhkj.txg.module.mine.adapter

import android.graphics.Paint
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.group.ui.GroupDetailActivity
import com.zhkj.txg.module.mine.entity.CollectionEntity
import com.zhkj.txg.module.mine.ui.CheckStatusEntity
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.utils.ImageUtils

class CollectionGoodsAdapter(
    private val onCheckChange: (checkStatus: CheckStatusEntity) -> Unit
) : BaseQuickAdapter<CollectionEntity, BaseViewHolder>(R.layout.item_collection_goods),
    LoadMoreModule {

    private val isMember = AccountManager.isMember()

    init {
        addChildClickViewIds(R.id.tvCollectionTagMatter, R.id.tvCollectionTagShareEarn)
        setOnItemClickListener { _, _, position ->
            if (editMode) {
                // 值取反
                data[position].goods?.selected = data[position].goods?.selected?.not() ?: false
                // 刷新视图
                notifyItemChanged(position)
                // 刷新状态
                refreshCheckStatus()
                // 回调,可刷新全选按钮状态
                onCheckChange(checkStatus)
            } else when (data[position].type) {
                0 -> ProductDetailActivity.normalProduct(
                    context, data[position].goods?.id?.toInt() ?: 0, true
                )
                else -> GroupDetailActivity.normalProduct(context, data[position].goods?.id?.toString() ?: "0")
            }
        }
    }

    /**
     * 判断UI是否需要进入编辑模式
     */
    var editMode = false
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    /**
     * 选中状态容器
     */
    val checkStatus = CheckStatusEntity()

    override fun convert(helper: BaseViewHolder, item: CollectionEntity) {
        item.goods?.let { product ->
            val imageView = helper.setText(R.id.tvCollectionGoodsName, product.goodsName)
                .setVisible(R.id.tvCateProductTag, product.isNew == "1")
                .setText(R.id.tvCollectionGoodsPrice, SpanUtil.setMoneySymbol(product.price, true))
                .setText(R.id.tvCollectionGoodsShopName, product.shopName)
                .setGone(R.id.ivCheck, !editMode)
                .getView<ImageView>(R.id.ivCollectionGoods)
            ImageUtils.loadRoundCornerImage(context, imageView, product.image)
            helper.itemView.isSelected = product.selected
            // 设置是显示市场价还是显示分享赚多少钱
            with(helper.getView<TextView>(R.id.tvCollectionGoodsMarketPrice)) {
                if (AccountManager.isMember() && product.shareEarn.isNotEmpty() && product.shareEarn != "0") {
                    setTextColor(ContextCompat.getColor(context, R.color.colorMain))
                    paint.flags = Paint.ANTI_ALIAS_FLAG
                    text = SpanUtil.setPrefixMoneyStr(price = product.shareEarn)
                } else {
                    setTextColor(ContextCompat.getColor(context, R.color.colorLightText))
                    paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    paint.isAntiAlias = true
                    text = SpanUtil.setMoneySymbol(product.marketPrice)
                }
            }
            // 判断是否显示标签
            helper.setGone(
                R.id.tvCollectionTagMatter,
                product.shareContent.isEmpty() && product.shareImages.isEmpty()
            )
            helper.setGone(
                R.id.tvCollectionTagShareEarn,
                !isMember || product.shareSwitch == null || product.shareSwitch != 1
            )
        }
    }

    fun refreshCheckStatus(
        needCheckAll: Boolean = false,
        checkAll: Boolean = false
    ): CheckStatusEntity {
        var checkAllTemp = true
        var checkAny = false
        data.forEach {
            // 如果需要设置全选，就先设置全选
            if (needCheckAll) it.goods?.selected = checkAll
            // 判断是否有全选，或者选中一个
            if (it.goods?.selected == true) checkAny = true
            else checkAllTemp = false
        }
        // 如果设置了全选，刷新列表
        if (needCheckAll) notifyDataSetChanged()
        return checkStatus.apply {
            this.allCheck = checkAllTemp
            this.checkAny = checkAny
        }
    }

    /**
     * 获取所有选中商品的id,用','隔开
     */
    fun getCheckedGoodsId(): String {
        return if (checkStatus.checkAny) {
            buildString {
                for (product in data)
                    if (product.goods?.selected == true) append(product.id).append(',')
                if (length > 0) deleteCharAt(lastIndex)
            }
        } else ""
    }
}